package com.wstuo.dwr;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.directwebremoting.Container;
import org.directwebremoting.ServerContextFactory;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.event.ScriptSessionEvent;
import org.directwebremoting.event.ScriptSessionListener;
import org.directwebremoting.extend.ScriptSessionManager;

/**
 * DWR 实现类
 * @author Ciel
 *
 */
public class DwrScriptSessionManagerUtil {
	private static final long serialVersionUID = -7504612622407420071L;
	/**
	 * 初始化
	 * @throws ServletException
	 */
	public void init()throws ServletException {
		Container container = ServerContextFactory.get().getContainer();
		ScriptSessionManager manager = container.getBean(ScriptSessionManager.class);
		ScriptSessionListener listener = new ScriptSessionListener() {
			public void sessionCreated(ScriptSessionEvent ev) {
				HttpSession session = WebContextFactory.get().getSession();
				Long userId =(Long) session.getAttribute("userId");
				ev.getSession().setAttribute("userId", userId);
			}
			public void sessionDestroyed(ScriptSessionEvent ev) {
				GetUserPageDwr.onlineUsers.remove(ev.getSession().getAttribute("userId"));
			}
		};
		manager.addScriptSessionListener(listener);
	}
}
